<template>
    <div class="template-detail-page">
        <el-card shadow="never" v-loading="loading">
            <div class="flex flex-wrap items-center justify-between mb-4" v-if="!(!companyId && form.company_id)">
                <div class="text-base mt-2 mb-2">使用该模板，创建我的学习地图</div>
                <div class="wrap-button flex flex-wrap items-center">
                    <el-button type="primary" @click="toGroup">组合多个学习地图</el-button>
                    <el-button v-if="!canEdit" type="primary" @click="onDownload">下载空模板</el-button>
                    <input @change="onChange" class="hidden" type="file" accept=".xlsx" ref="file">
                    <el-button v-if="!canEdit" for="file-input" type="primary" @click="onImport">导入用模板编写的内容</el-button>
                    <el-button type="primary" v-if="!canEdit" @click="onSave('save')">保存当前内容</el-button>
                    <el-button
                        v-if="!companyId && !form.is_template"
                        @click="onSave('done')"
                        type="primary">设置为企业可见模板</el-button>
                    <el-button
                        v-if="!companyId && form.is_template"
                        @click="onSave('done', true)"
                        type="primary">取消设置为企业可见模板</el-button>
                    <el-button
                        @click="onReuse"
                        type="primary"
                        v-if="id && (!form.company_id && companyId)">使用该模板</el-button>
                    <el-button v-if="roleType" @click="onCreateCourse" type="primary">部署为选课中心</el-button>
                    <el-button type="primary" @click="onExport">导出到本地</el-button>
                    <el-button @click="onCreateData" type="primary">部署为学习路径</el-button>
                </div>
            </div>
            <el-form
                label-position="right"
                label-suffix=":"
                label-width="50px"
                :disabled="canEdit"
            >
                <el-form-item label="标题">
                    <el-input
                        v-model.trim="form.title"
                        placeholder="请输入模板的标题"
                        class="input-width"></el-input>
                </el-form-item>
                <el-form-item label="描述" class="border-b">
                    <el-input
                        v-model.trim="form.describe"
                        placeholder="请输入模板的描述"
                        class="input-width"></el-input>
                </el-form-item>
            </el-form>
            <el-table :data="data" :cell-class-name="cellStyle" :header-row-class-name="rowStyle">
                <el-table-column align="center" label="序号" width="100">
                    <el-table-column align="center" width="100">
                        <template slot-scope="{$index}">
                            <div v-if="$index !== data.length - 1">{{ $index + 1 }}</div>
                            <div
                                v-else
                                @click="onAddClick('add')"
                                class="flex items-center justify-center add p-4 cursor-pointer">
                                <div v-if="canAddAndRemove" class="el-icon-plus">新增</div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="学习阶梯/主题分类" width="160">
                    <el-table-column align="center" label="描述主题的难易或分类" width="160">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model.trim="row.label"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="场景主题" width="250">
                    <el-table-column align="center" label="用关键词或短语概括工作场景或主题" width="250">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model="row.course"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="工作场景描述" width="230">
                    <el-table-column align="center" label="清晰的描述工作场景" width="230">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model="row.describe"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="岗位工作职责任务" width="330">
                    <el-table-column align="center" label="描述该工作场景的工作事项、任务、工作流程等" width="330">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model="row.detail"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="岗位工作能力及技术、知识要求" width="450">
                    <el-table-column
                        align="center"
                        label="描述胜任该工作场景日常工作需要具备的能力、技术、知识等"
                        width="450">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model="row.capability"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="学习内容和收获" width="200">
                    <el-table-column align="center" label="" width="200">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model="row.benefit"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="培训计划清单" width="200">
                    <el-table-column align="center" label="" width="200">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model="row.list"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="备注/学习建议" width="130">
                    <el-table-column align="center" label="" width="130">
                        <template slot-scope="{$index, row}">
                            <el-input
                                v-if="$index !== data.length - 1"
                                type="textarea"
                                autosize
                                :disabled="canEdit"
                                v-model="row.note"></el-input>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column align="center" label="操作" width="100">
                    <el-table-column align="center" label="" width="100">
                        <template slot-scope="{$index}">
                            <el-button
                                v-if="canAddAndRemove && $index !== data.length - 1"
                                type="text"
                                :disabled="canEdit"
                                @click="onAddClick('delete', $index)"
                                class="red-color">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
        </el-card>
        <div class="mt-4 text-center">
            <el-button @click="onReturn">返 回</el-button>
        </div>
    </div>
</template>

<script>

export default {
    components: {
    },
    inject: ['reload'],
    data() {
        return {
            id: '',
            companyId: '',
            isShow: false,
            loading: false,
            form: {
                title: '',
                describe: '',
                is_template: false,
                content_list: [],
            },
            data: [{}],
            baseUrl: process.env.VUE_APP_API_PREFIX,
        };
    },
    watch: {
        $route() {
            // 刷新
            this.reload();
        },
    },
    computed: {
        canEdit() {
            return this.companyId ? !!this.id && (this.companyId !== this.form.company_id) : false;
        },
        my() {
            return this.$store.state.my;
        },
        roleType() {
            return this.my && this.my.type === 1;
        },
        canAddAndRemove() {
            return !(!this.companyId && this.form.company_id)
                && (this.my.type === 2 || this.my.id === this.form.admin_id);
        },
    },
    methods: {
        // 生成模板、保存
        onSave(e, isCanel, noTip) {
            const data = [...this.data];
            const form = {...this.form};

            let method = 'post';
            let url = 'template';
            let text = '保存成功';

            data.splice(-1, 1);
            form.content_list = data;
            if (e === 'done') {
                text = '操作成功';
                form.is_template = !isCanel;
                this.form.is_template = !isCanel;
            }

            if (this.id) {
                method = 'put';
                url = `template/${this.id}`;
            }

            this.loading = true;
            API[method](url, form).then(res => {
                if (!noTip) $ele.$message.success(text);
                if (typeof res === 'number') this.replace(res);
            }).finally(() => this.loading = false);
        },
        onAddClick(text, index) {
            if (this.canEdit) return;

            if (text === 'add') {
                this.data.splice(this.data.length - 1, 0, {
                    label: '',
                    course: '',
                    describe: '',
                    detail: '',
                    capability: '',
                    benefit: '',
                    list: '',
                    note: '',
                });
            } else this.data.splice(index, 1);
        },
        // 复用模板
        onReuse() {
            this.loading = true;
            const form = {...this.form};
            form.is_template = false;
            delete form.company_id;
            delete form.id;
            API.post('template', form).then(() => {
                $ele.$message.success('复用模板成功');
                this.onReturn();
            }).finally(() => this.loading = false);
        },
        // 导出
        onExport() {
            if (this.id) return window.location.href = `${this.baseUrl}template/export/${this.id}`;

            const data = [...this.data];
            const form = {...this.form};

            data.splice(-1, 1);
            form.content_list = data;

            this.loading = true;
            // 创建模板记录
            API.post('template', form).then(res => {
                // 下载
                window.location.href = `${this.baseUrl}template/export/${res}`;
                // 下载后删除记录
                API.delete(`template/${res}`).finally(() => this.loading = false);
            }).catch(() => this.loading = false);
        },
        // 生成数据
        onCreateData() {
            if (!this.isShow) return $ele.$message('进阶功能联系我们单独开通');

            let data = [...this.data];
            let form = {...this.form};

            data.splice(-1, 1);

            data = data.filter(val => {
                let noEmpty = false;
                for (const key in val) {
                    if (Object.hasOwnProperty.call(val, key)) {
                        noEmpty = !!val[key];
                        if (noEmpty) break;
                    }
                }

                if (noEmpty) return val;
                return false;
            });

            form.content_list = data;

            let method = 'post';
            let url = 'template/gen';

            if (this.id) {
                method = 'put';
                url = `template/gen/${this.id}`;
                form = '';
            }

            this.loading = true;
            API[method](url, form).then(res => {
                if (res) {
                    $ele.$message.success('生成数据成功');
                } else $ele.$message.success('生成数据失败');
            }).finally(() => this.loading = false);
        },

        // 选课生成数据
        onCreateCourse() {
            let data = [...this.data];
            let form = {...this.form};

            data.splice(-1, 1);
            data = data.filter(val => {
                let noEmpty = false;
                for (const key in val) {
                    if (Object.hasOwnProperty.call(val, key)) {
                        noEmpty = !!val[key];
                        if (noEmpty) break;
                    }
                }
                if (noEmpty) return val;
                return false;
            });
            form.content_list = data;

            let url = 'template/elective';
            if (this.id) {
                url = `template/elective/${this.id}`;
                form = '';
            }

            this.loading = true;
            API.post(url, form).then(res => {
                if (res) {
                    $ele.$message.success('生成数据成功');
                } else $ele.$message.success('生成数据失败');
            }).finally(() => this.loading = false);
        },

        // 表格主体，行的类名
        cellStyle(row) {
            if (row.columnIndex) return `unMiddle unMiddle-${row.columnIndex}-${row.rowIndex}`;
        },
        // 表头的类名
        rowStyle(row) {
            if (row.rowIndex) return 'header-style';
        },

        // 获取数据
        fetchData() {
            this.loading = true;
            API.get(`template/${this.id}`).then((res) => {
                this.form = res;
                if (res.content_list && res.content_list.length) {
                    this.data = [...res.content_list, {}];
                }
            }).finally(() => {
                this.loading = false;
            });
        },
        // 替换当前路由
        replace(id) {
            this.$router.replace({
                name: 'Template.Detail',
                query: {
                    id,
                },
            });
        },

        onReturn() {
            this.$router.back();
        },

        onImport() {
            this.$refs.file.click();
        },
        onChange(event) {
            this.loading = true;
            const formData = new FormData();
            formData.append('file', event.target.files[0]);
            API.post('excel/import', formData)
                .then(res => {
                    if (res) {
                        this.form.title = res.title;
                        this.form.describe = res.describe;
                        this.form.content_list = res.content_list || [];
                        this.data = [...res.content_list, {}];
                    }
                })
                .finally(() => {
                    event.target.value = '';
                    this.loading = false;
                });
        },

        onDownload() {
            window.location.href = `${API.base_url}excel/download`;
        },

        toGroup() {
            if (!this.isShow) return $ele.$message('进阶功能联系我们单独开通');

            const params = this.id ? {id: this.id} : '';
            const form = this.form;

            sessionStorage.setItem('templateData', JSON.stringify({
                title: form.title,
                describe: form.describe,
            }));

            this.$router.push({
                name: 'Template.Group',
                params: params,
            });
        },
    },
    mounted() {
        const id = this.$route.query.id;

        if (id) {
            this.id = id;
            this.fetchData();
        } else {
            const list = [];
            // 默认十条数据
            for (let index = 0; index < 10; index++) {
                list.push({
                    label: '',
                    course: '',
                    describe: '',
                    detail: '',
                    capability: '',
                    benefit: '',
                    list: '',
                    note: '',
                });
            }
            this.data = [...list, ...this.data];
        }

        let companyId = '';
        const profile = sessionStorage.getItem('my/profile') ? JSON.parse(sessionStorage.getItem('my/profile')) : '';
        if (profile) {
            companyId = profile.company_id;
            // 是否有『学习路径管理』权限
            this.isShow = profile.permission.includes(5) || !companyId;
        }
        // 公司id
        this.companyId = companyId;

        // 事件绑定
        const tableNode = document.querySelector('.el-table');
        tableNode.addEventListener('click', (e) => {
            const nodeName = e.target.className.split(' ');
            if (nodeName.length && nodeName[nodeName.length - 1].includes('unMiddle')) {
                const textarea = document.querySelector(`.el-table .${nodeName[nodeName.length - 1]} .el-textarea`);
                // 获得焦点
                if (textarea) textarea.firstChild.focus();
            }
        });
    },
};
</script>

<style lang="scss">
.template-detail-page {
    .el-form-item {
        margin: 0;
        padding: 10px 0;
        border-top: 1px solid #e2e8f0;
    }

    .el-input input,
    .el-textarea__inner {
        border: none;
    }

    .add {
        color: rgb(24, 144, 255);
    }

    .el-table th, .el-table tr,
    .el-table--enable-row-hover .el-table__body tr:hover>td {
        background: white;
    }

    .unMiddle {
        vertical-align: top;
    }

    thead {
        .header-style th.is-leaf {
            background: white;
            color: rgb(153, 153, 153);
        }
    }

    .el-textarea.is-disabled .el-textarea__inner,
    .el-input.is-disabled .el-input__inner {
        font-weight: 600;
        background-color: #fdfdfd;
    }

    .el-table--scrollable-x .el-table__body-wrapper {
        overflow-x: scroll;
    }

    .el-table {
        ::-webkit-scrollbar {
            width: 5px;
            height: 10px;
        }

        ::-webkit-scrollbar-thumb {
            border-radius: 1em;
            background-color: rgba(50, 50, 50, .3);
        }

        ::-webkit-scrollbar-track {
            border-radius: 1em;
            background-color: rgba(50, 50, 50, .1);
        }
    }

    .wrap-button .el-button {
        margin: 0.25rem;
    }
}
</style>
